﻿using System.Xml;
using System.Xml.Linq;

namespace DotNet.Common.Extensions.Xml
{
        public static class XmlExtensions
        {
                /// <summary>
                /// XElement(Linq)转换为XmlElement
                /// </summary>
                /// <param name="xElement"></param>
                /// <returns></returns>
                public static XmlElement ToXmlElement(this XElement xElement)
                {
                        if (xElement == null) return null;

                        XmlElement xmlElement = null;
                        XmlReader xmlReader = null;
                        try
                        {
                                xmlReader = xElement.CreateReader();
                                var doc = new XmlDocument();
                                xmlElement = doc.ReadNode(xElement.CreateReader()) as XmlElement;
                        }
                        catch { throw; }
                        finally
                        {
                                if (xmlReader != null) xmlReader.Close();
                        }

                        return xmlElement;
                }

                /// <summary>  
                /// XmlElement转换为XElement(Linq)
                /// </summary>  
                public static XElement ToXElement(this XmlElement xmlElement)
                {
                        if (xmlElement == null) return null;

                        XElement xElement = null;
                        try
                        {
                                var doc = new XmlDocument();
                                doc.AppendChild(doc.ImportNode(xmlElement, true));
                                xElement = XElement.Parse(doc.InnerXml);
                        }
                        catch { throw; }

                        return xElement;
                }
        }
}
